﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MedicalManagementSystem.Utils;
using MedicalManagementSystem.Models;

namespace MedicalManagementSystem.Utils
{
    public class GenericController : Controller
    {
        protected void AddViolataionsToModelState(RuleViolationException ruleException)
        {
            AddViolataionsToModelState(ruleException.Violations);
        }

        protected void AddViolataionsToModelState(IEnumerable<IRuleViolation> ruleViolations)
        {
            foreach (var ruleViolation in ruleViolations)
            {
                ModelState.AddModelError(ruleViolation.PropertyName, ruleViolation.ErrorMessage);
                ModelState.SetModelValue(ruleViolation.PropertyName,
                                         new ValueProviderResult(ruleViolation.PreviousValue,
                                                                 ruleViolation.AttemptedValue, null));
            }
        }

        protected void ClearModelStateErrors()
        {
            ModelState.Values.Where(state => state.Errors.Count > 0).Each(state => state.Errors.Clear());
        }
    }
}
